// component/home/com-home-banner/com-home-banner.js
import api from "../../../common/api.js";
import p from "../../../utils/platform";
import constant from "../../../common/constant.js";
import { collaborateLog } from "../../../common/log.js";

const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    model: {
      type: Array,
      value: [],
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentIndex: 0,
  },

  lifetimes: {
    attached: function () {
      app.globalData.bannerComponent = this;
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleChangeIndex(e) {
      this.setData({
        currentIndex: e.detail.current,
      });

      this.triggerEvent("changecurrentbannerindex", this.data.currentIndex);
    },
    handleGo(e) {
      const index = e.currentTarget.dataset.index;
      const activityCode = this.data.model[index].activityCode;
      const isProgram = this.data.model[index].linkWay;
      this.gotoActivity(activityCode, isProgram);
    },

    gotoActivity(activityCode, isProgram, entrance = 0) {
      const index = this.data.model.findIndex((item) => {
        return item.activityCode == activityCode;
      });
      const info = this.data.model[index];
      if (!info.linkUrl) return;
      wx.gio("track", constant.HP_FLOOR_CLICK, {
        [constant.RESOURCE_VAR]: info.imgName,
        [constant.POSITION_VAR]: index,
      });
      // 合作房源
      if (activityCode == "collaborate") {
        collaborateLog({
          method: entrance,
        });
      }

      // 必须授权手机号的活动
      if (info.login == 1) {
        const fn = (routerMethod) => {
          if (isProgram == "program") {
            routerMethod({
              url: info.linkUrl + "?actEntre=firstSwiper",
            });
            return;
          }
          const { shareImgUrl = "" } = info;
          const url = `/pages/webView/webView?webViewUrl=${info.linkUrl}&login=1&activityName=${info.imgName}&activityCode=${info.activityCode}&shareImgUrl=${shareImgUrl}`;
          // console.log('url =>', url);

          routerMethod({ url });
        };
        app
          .mobileLogin()
          .then(() => {
            fn(p.navigateTo);
          })
          .catch(() => {
            app.globalData.afterMobileAuthorCallBack = () => {
              fn(p.reLaunch);
            };
          });
          
      } else {
        if (isProgram == "program") {
          wx.navigateTo({
            url: info.linkUrl,
          });
          return;
        }
        let mobile = app.globalData.sessionUser.mobile;
        if (mobile) {
          p.navigateTo({
            url: `/pages/webView/webView?webViewUrl=${info.linkUrl}&mobile=${mobile}`,
          });
        } else {
          p.navigateTo({
            url: `/pages/webView/webView?webViewUrl=${info.linkUrl}`,
          });
        }
      }
    },
  },
});
